<?php
/**
 * 后台分类管理
 * @package app\admin\controller
 * User: Administrator
 * Date: 2018/10/26 0013
 * Time: 14:55
 */
namespace app\admin\controller;

use service\DataService;
use service\NodeService;
use service\ToolsService;
use think\Db;
use think\Loader;
use think\Request;

class Category extends BasicAdmin
{

    public $table = 'ml_cate';

    /**
     * 分类列表
     */
    public function index()
    {
        $this->title = '网站配置 > 类目管理';
        if($this->request->isPost()){
            $db = Db::name($this->table)->where('pid',0)->order('sort desc,id desc');
            $params = [];
            return parent::_list($db,$params);
        }
        return $this->fetch('',['title'=>$this->title]);
    }

    /**
     * 获取子分类列表
     */
    public function soncate(){
        if($this->request->isPost()){
            $param['pid'] = $this->request->post('pid','','trim');
            $db = Db::name($this->table)->where('pid',$param['pid'])->order('sort asc,id asc');
           return parent::_list($db,$param,false);
        }
    }

    /**
     * 添加分类
     */
    public function add()
    {
        return $this->_form($this->table, 'form');
    }

    /**
     * 编辑分类
     */
    public function edit()
    {
        if($this->request->isPost()){
            if($rst = DataService::update($this->table)){
                //更新前端分类缓存列表
                updata_cate_date();
            }
            $msg = doReturn('更新成功','更新失败',$rst);
            $this->resultArr($msg);
        }
    }

    /**
     * 表单数据前缀方法
     * @param array $vo
     */
    protected function _form_filter(&$vo)
    {
        if ($this->request->isGet()) {
            // 上级菜单处理
            $_cates = Db::name($this->table)->order('sort desc,id desc')->select();
            $_cates[] = ['cate' => '顶级菜单', 'id' => '0', 'pid' => '-1'];
            $cates = ToolsService::arr2table($_cates);
            $this->assign('cates', $cates);
        }
    }

    /**
     * 表单数据后置方法
     * @param $data
     */
    protected function _form_result(&$result){
        if($result !== false){
            updata_cate_date();
        }
    }

    /**
     * 删除分类
     */
    public function del()
    {
        if($this->request->isPost()){
            $data = array_filter($this->request->post());
            $validate = Loader::validate('Cate');
            if(!$validate->scene('delete')->check($data)){
                $this->result(null,'0',$validate->getError(),'json');
            }else{
                if($status = DataService::update($this->table)){
                    updata_cate_date();
                }
                $ret = doReturn('分类删除成功！','分类删除失败, 请稍候再试!',$status,[],'json');
                $this->resultArr($ret);
            }
        }
    }
}
